/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { isEqual } from 'lodash';

export type Request = (o: any, fromRedDot?: boolean) => Promise<any>;
export type Refresh = (o: RequestOptions) => void;
export interface RequestOptions {
  pathname: string;
  type: string;
}

interface CacheItem {
  refresh: Refresh;
  options: RequestOptions;
}

/**
 *
 * @description 红点请求缓存记录
 * checkRepeatOptions 检查options是否重复
 * get 获取缓存
 * set 设置缓存
 * refresh 刷新红点
 */

class RedPointRequestCache {
  cache: Map<any, any>;
  constructor() {
    this.cache = new Map();
  }
  checkRepeatOptions(pre: RequestOptions, cur: RequestOptions): boolean {
    return isEqual(pre, cur);
  }
  get(request: Request): CacheItem[] | undefined {
    return this.cache.get(request);
  }
  set(request: Request, refresh: Refresh, options: RequestOptions) {
    let cache = this.get(request);
    const params = { refresh, options };
    if (cache && !this.checkRepeatOptions(cache[0].options, options)) {
      cache.push(params);
    } else {
      cache = [params];
    }
    this.cache.set(request, cache);
  }
  refresh(request: Request, enableRefresh: boolean = true) {
    // 是否允许
    if (enableRefresh) {
      const list = this.get(request);
      if (list) {
        list.forEach((item) => {
          item.refresh(item.options);
        });
      }
    }
  }
}

export default RedPointRequestCache;
